package com.exp.security.config;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangxj
 * @date 2025/1/4
 * @Description
 */
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");

        // 将结果转换成 json 字符串
        Map<String, Object> result = new HashMap();
        result.put("code", 400);
        result.put("msg", "登录失败，" + exception.getLocalizedMessage());
        String responseJson = JSONUtil.toJsonStr(result);
        response.getWriter().write(responseJson);
    }
}
